import axios from 'axios';
import host from '../utils/host';
import { Message } from 'element-ui'

const service = axios.create({
  // process.env.NODE_ENV === 'development' 来判断是否开发环境
  baseURL: host.host,
  // baseURL: process.env.NODE_ENV === 'development' ? 'http://192.168.0.100:8090/api' : 'http://192.168.1.100:8090/api',//林老师
  timeout: 60000000
});

service.interceptors.request.use(config => {
  const token = sessionStorage.getItem('token');
  config.headers = token ? { 'Token': sessionStorage.getItem('token') } : '';
  if (config.ContentType) {
    config.headers['Content-Type'] = config.ContentType;
    delete config.ContentType
  }
  return config;
}, error => {
  return Promise.reject();
});

service.interceptors.response.use(response => {
  if (response.status === 200) {
    if (response.data.code === 200 || response.data.code === 100) {
      return response.data;
    }
    else {
      Message({
        message: response.data.message,
        type: 'error',
        duration: 2 * 1000
      });
      return Promise.reject(error);
    }
  }


  else {
    return Promise.reject();
  }
}, error => {
  if (String(error).includes('Network Error')) {
    Message({
      message: '网络出错了,请检查网络',
      type: 'error',
      duration: 2 * 1000
    });
    return Promise.reject(error);
  } else if (error.response.status === 500 || error.response.status === 403) {
    Message({
      message: '登录已失效，请重新登录',
      type: 'error',
      duration: 2 * 1000
    });
    setTimeout(function () {
      sessionStorage.removeItem('resources');
      sessionStorage.removeItem('token');
      sessionStorage.removeItem('adminUserInfo');
      window.location.href = process.env.NODE_ENV === 'development' ? window.location.protocol + "//" + window.location.host + '/#/login' : window.location.protocol + "//" + window.location.host + process.env.VUE_APP_HOST + '#/login';
    }, 2000)
  } else {
    Message({
      message: error.response.data.message,
      type: 'error',
      duration: 2 * 1000
    });
    return Promise.reject(error);
  }
});

export default service;
